package com.earthchen.demo.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.earthchen.core.base.BaseController;
import com.earthchen.core.util.JsonWebTokenUtil;
import com.earthchen.core.vo.ResultVO;
import com.earthchen.demo.domain.SysUser;
import com.earthchen.demo.domain.SysUserRole;
import com.earthchen.demo.dto.AuthorityUserRoleDTO;
import com.earthchen.demo.dto.PageParamDTO;
import com.earthchen.demo.service.SysUserRoleService;
import com.earthchen.demo.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author earthchen
 * @date 2018/9/6
 **/
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private SysUserService userService;


    @Autowired
    private SysUserRoleService sysUserRoleService;


    /**
     * 获取对应用户角色
     *
     * @param appId
     * @return
     */
    @GetMapping("/role/{appId}")
    public ResultVO getUserRoleList(@PathVariable String appId) {
        String roles = userService.selectUserRoles(appId);
        Set<String> roleSet = JsonWebTokenUtil.split(roles);
        Map<String, Object> map = new HashMap<>(1);
        map.put("roles", roleSet);
        return ResultVO.success(map);
    }


    /**
     * 分页获取用户信息
     *
     * @param pageParamDTO
     * @return
     */
    @GetMapping("/list")
    public ResultVO getUserList(PageParamDTO pageParamDTO) {
        Page<SysUser> page = new Page<>(pageParamDTO.getPage(), pageParamDTO.getSize());
        Page<SysUser> sysUserPage = userService.selectPage(page);
        return ResultVO.success(sysUserPage);
    }


    /**
     * 给用户授权添加角色
     *
     * @param authorityUserRoleDTO
     * @return
     */
    @PostMapping("/authority/role")
    public ResultVO authorityUserRole(AuthorityUserRoleDTO authorityUserRoleDTO) {
        userService.authorityUserRole(authorityUserRoleDTO.getUserId(),
                authorityUserRoleDTO.getRoleId());
        return SUCCESS;
    }

    /**
     * 删除已经授权的用户角色
     *
     * @param uid
     * @param roleId
     * @return
     */
    @DeleteMapping("/authority/role/{uid}/{roleId}")
    public ResultVO deleteAuthorityUserRole(@PathVariable String uid, @PathVariable Integer roleId) {
        sysUserRoleService.delete(new EntityWrapper<SysUserRole>()
                .where("user_id={0} and role_id={1}", uid, roleId));
        return SUCCESS;
    }


}
